package tests.cases {
	
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.utils.ObjectUtil;
	
	import org.flexunit.Assert;
	import org.flexunit.async.Async;
	import org.flexunit.async.TestResponder;
	
	/**
	 * The base class of all system test cases.
	 */
	public class DefaultTestCase {
		
		/** The number of milliseconds a request has to complete in before timing out. */
		protected var timeout:int = 5000;
		
		/**
		 * Invoked to handle fault events.
		 * @param message The message detail of the fault.
		 * @param passedData The arguments originally passed to the function.
		 */
		private function handleFault(message:FaultEvent, passedData:Object):void {
			
			Assert.fail(
				"The following fault has occured whilst executing the test:" +
				"\n---------------------------------------------------------\n" +
				ObjectUtil.toString(message.fault)
			);
		}
		
		/**
		 * Invoked to handle request timeout events.
		 * @param passedData The arguments originally passed to the function.
		 */
		private function handleTimeout(passedData:Object):void {
			
			Assert.fail("The test took longer than " + timeout + " milliseconds to complete and has subsequently been timed out.");
		}
		
		/**
		 * Executes an asynchronus test.
		 * @param token The async token to attach responders to.
		 * @param argsVO The arguments passed to the test.
		 * @param resultHandler The function to invoke if the test completes successfully.
		 * @param faultHandler The function to invoke if the test fails to complete.
		 * @param timeoutHandler The function to invoke if the test times out.
		 */
		protected function runAsyncTest(token:AsyncToken, argsVO:Object, resultHandler:Function, faultHandler:Function=null, timeoutHandler:Function=null):void {
			
			var responder:IResponder = Async.asyncResponder(
				this,
				new TestResponder(resultHandler, (faultHandler == null? handleFault:faultHandler)),
				timeout,
				argsVO,
				(timeoutHandler == null? handleTimeout:timeoutHandler)
			);
			token.addResponder(responder);
		}
	}
}